import { defineStore } from "pinia"
import { userLogin , userlist} from '@/api/index'
import router from '@/router'
import  { ElMessage } from 'element-plus'  

export const useloginStore = defineStore('login',{ 
    state:()=>{
        return{  
            token:'',  
            UserListData:{
                items:[],
                total:0,
            },
        }
    },
    actions: {
        // 登录
        async Login(username:string,password:string){
            let result = await userLogin({username,password})
            if (result.code == 20000) {
                this.token = result.data.token
                ElMessage.success('登录成功')
                router.push('/') 
            }else if(result.message){  
                ElMessage.error(result.message)
            }else{
                ElMessage.error('用户不存在或者密码错误!')
            }
        },
        // 获取用户列表
        async UserList(page:number,limit:number,username?:string){
            let result = await userlist({page,limit,username})
            if (result.code == 20000) {
                this.UserListData = result.data 
            }else{
                ElMessage.error('获取用户列表失败!')
            }
        }
    },
    // 持久化存储
    // 持久化数据插件需要提前安装
    // import piniaPluginPersist from 'pinia-plugin-persist'
    persist:{
        enabled:true,
        strategies: [
            {
                key: 'token',//设置存储的key
                /* storage: localStorage,//表示存储在localStorage
                paths: token,//指定要长久化的字段 */
                storage: sessionStorage,
                paths: ['token']
            }
        ]
    }
})